package com.qianchang.microfinance.view.credit.data.facerecoder;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dm.library.widgets.element.DTextView;
import com.dm.library.widgets.statusbar.StatusBarUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.credit.data.ScanFaceActivity;

import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述:
 * 修 改 人: zhoulai
 * 修改时间: 2017/9/11 17:24
 */


public class FaceVideoRecordActivity extends BaseActivity {

    private static final String TAG        = "FaceVideoRecordActivity";
    public static final  String VIDEO_PATH = "video_path";
    @BindView(R.id.tv_chunyu)
    DTextView tvChunyu;

    private MediaUtils       mediaUtils;
    private VideoProgressBar mainProgress;
    private int              mProgress;
    private TextView         tvPressControl;
    private SendView         viewSend;
    private RelativeLayout   recordLayout;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_record);
        ButterKnife.bind(this);
        StatusBarUtil.setTranslucentForImageViewInFragment(FaceVideoRecordActivity.this, null);
        viewSend = (SendView) findViewById(R.id.view_send);
        SurfaceView mainSurfaceView = (SurfaceView) findViewById(R.id.main_surface_view);

        // setting
        mediaUtils = new MediaUtils(this);
        mediaUtils.setRecorderType(MediaUtils.MEDIA_VIDEO);      //Environment.DIRECTORY_MOVIES
        mediaUtils.setTargetDir(Environment.getExternalStorageDirectory());
        mediaUtils.setTargetName(UUID.randomUUID() + ".mp4");
        //        mediaUtils.setTargetName("a123" + ".mp4");
        mediaUtils.setSurfaceView(mainSurfaceView);

        mainProgress = (VideoProgressBar) findViewById(R.id.main_progress_bar);
        tvPressControl = (TextView) findViewById(R.id.main_press_control);
        tvPressControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaUtils.record();
                startView();
                tvPressControl.setEnabled(false);
            }
        });
        recordLayout = (RelativeLayout) findViewById(R.id.record_layout);

        mainProgress.setOnProgressEndListener(listener);
        mainProgress.setCancel(true);

        viewSend.backLayout.setOnClickListener(backClick);
        viewSend.selectLayout.setOnClickListener(selectClick);
        initData();
    }


    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (null != bundle) {
            String validateData = bundle.getString(ScanFaceActivity.VALIDATE_DATA);
            tvChunyu.setTextContent(validateData);
        }
    }


    VideoProgressBar.OnProgressEndListener listener = new VideoProgressBar.OnProgressEndListener() {
        @Override
        public void onProgressEndListener() {
            mainProgress.setCancel(true);
            tvPressControl.setEnabled(true);
            mediaUtils.stopRecordSave();
            stopView(true);
        }
    };


    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mainProgress.setProgress(mProgress);
                    if (mediaUtils.isRecording()) {
                        mProgress = mProgress + 1;
                        sendMessageDelayed(handler.obtainMessage(0), 50);
                    }
                    break;
            }
        }
    };


    @Override
    protected void onPause() {
        super.onPause();
        mainProgress.setCancel(true);
        tvPressControl.setEnabled(true);
        mediaUtils.stopRecordUnSave();
        stopView(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //按两次返回退出应用程序
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            handler.removeCallbacksAndMessages(null);
            if (null != mediaUtils) {
                mediaUtils.stopRecordUnSave();
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    private void startView() {
        startAnim();
        mProgress = 0;
        handler.removeMessages(0);
        handler.sendMessage(handler.obtainMessage(0));
    }


    private void stopView(boolean isSave) {
        stopAnim();
        mainProgress.setCancel(true);
        mProgress = 0;
        handler.removeMessages(0);
        if (isSave) {
            recordLayout.setVisibility(View.GONE);
            viewSend.setVisibility(View.VISIBLE);
            viewSend.startAnim();
        }
    }

    private void startAnim() {
        AnimatorSet set = new AnimatorSet();
        set.playTogether(
                ObjectAnimator.ofFloat(tvPressControl, "scaleX", 1, 0.5f),
                ObjectAnimator.ofFloat(tvPressControl, "scaleY", 1, 0.5f),
                ObjectAnimator.ofFloat(mainProgress, "scaleX", 1, 1.3f),
                ObjectAnimator.ofFloat(mainProgress, "scaleY", 1, 1.3f)
        );
        set.setDuration(250).start();
    }

    private void stopAnim() {
        AnimatorSet set = new AnimatorSet();
        set.playTogether(
                ObjectAnimator.ofFloat(tvPressControl, "scaleX", 0.5f, 1f),
                ObjectAnimator.ofFloat(tvPressControl, "scaleY", 0.5f, 1f),
                ObjectAnimator.ofFloat(mainProgress, "scaleX", 1.3f, 1f),
                ObjectAnimator.ofFloat(mainProgress, "scaleY", 1.3f, 1f)
        );
        set.setDuration(250).start();
    }


    private View.OnClickListener backClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            viewSend.stopAnim();
            recordLayout.setVisibility(View.VISIBLE);
            mediaUtils.deleteTargetFile();
        }
    };

    private View.OnClickListener selectClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            viewSend.stopAnim();
            recordLayout.setVisibility(View.VISIBLE);
            String path = mediaUtils.getTargetFilePath();
            Intent intent = new Intent();
            intent.putExtra(VIDEO_PATH, path);
            setResult(RESULT_OK, intent);
            finish();
        }
    };


}
